import { ref, type Ref, h, onMounted, toRaw } from "vue";
import {
  getOrderDetail,
  setGoodsSupplier,
  setOrderDeliver
} from "@/api/dashboard";

import { addDialog } from "@/components/ReDialog";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import { message } from "@/utils/message";
import SupplierForm from "../form/supplier.vue";
import DeliverForm from "../form/deliver.vue";
import DunningForm from "../form/dunning.vue";
import { copyTextToClipboard } from "@pureadmin/utils";
import {
  createDunningRecord,
  queryDunningRecord,
  updateDunningRecord
} from "@/api/dunning";
import dayjs from "dayjs";
import { title } from "process";

const orderDetail: any = ref({});
const receiptinfo: any = ref({});
const productinfo = ref([]);
const orderStatus = ref(0);
const totalprice = ref(0);

const deliverCost = ref(0);
const purchaseCosts = ref(0);
/** 表格数据展示 */
export function useTable(orderId, tableRef: Ref) {
  // ⚙️状态初始化
  const formRef = ref();
  /** 是否处于 Loding 状态 */
  const loading = ref(false);
  /** 多选操作 */
  const selectedNum = ref(0);
  /** 表格字段信息 */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "商品ID",
      prop: "fgoodsid",
      hide: true
    },
    {
      label: "货号",
      prop: "fgoodcode"
    },
    {
      label: "商品名称",
      prop: "fgoodname"
    },
    {
      label: "品牌",
      prop: "fbrand"
    },
    {
      label: "单位",
      prop: "funit",
      hide: true
    },
    {
      label: "数量",
      prop: "fquantity"
    },
    {
      label: "单价",
      prop: "fprice"
    },
    {
      label: "售价",
      prop: "fbidprice"
    },
    {
      label: "总价",
      prop: "totalprice"
    },
    {
      label: "采购价",
      prop: "purchaseprice"
    },
    {
      label: "支付方式",
      prop: "paymethod",
      hide: true
    },
    {
      label: "供应商",
      prop: "suppliername",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        console.log("输出信息");
        console.log(row);
        /** 未填写物流信息展示 */
        if (!row.suppliername) {
          let title = "设置商品供货商信息";
          return (
            <a
              style={{
                color: "#e6a23c",
                backgroundColor: "#fdf6ec",
                padding: "4px 8px",
                borderRadius: "4px",
                cursor: "pointer"
              }}
              onClick={() => handlerSetSupplierInfo(row)}
            >
              暂无
            </a>
          );
        }
        return (
          <div onClick={() => handlerSetSupplierInfo(row)}>
            {row.suppliername}
          </div>
        );
      }
    },
    {
      label: "物流状态",
      prop: "logisticsstates",
      minWidth: 90,
      cellRenderer: ({ row }) => {
        /** 未填写物流信息展示 */
        if (!row.logisticsstates) {
          return (
            <a
              style={{
                color: "#e6a23c",
                backgroundColor: "#fdf6ec",
                padding: "4px 8px",
                borderRadius: "4px",
                cursor: "pointer"
              }}
              onClick={() => singleSelectionFun(row.fgoodsid)}
            >
              暂无
            </a>
          );
        }
        return <div> {row.logisticsstates}</div>;
      }
    },
    {
      label: "收件费用",
      prop: "receiveSideFreight",
      hide: true
    },
    {
      label: "寄件费用",
      prop: "sendSideFreight",
      hide: true
    }
  ];
  /** 取消批量设置选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }
  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 获取订单详情数据 */
  function getOrderData(orderId) {
    getOrderDetail(orderId).then(res => {
      orderDetail.value = res.data;
      orderDetail.value.orderdate = dayjs(orderDetail.value.orderdate).format(
        "YYYY-MM-DD"
      );
      receiptinfo.value = res.data.receiptinfo;
      productinfo.value = res.data.productinfo;
      totalprice.value = res.data.price;
      purchaseCosts.value = res.data.expenditure.purchase_costs;
      deliverCost.value = res.data.expenditure.deliver_cost;
      orderStatus.value = getOrderStatus(res.data.status);
      // getSpanArr(productinfo.value);
    });
  }

  /**
   *  批量设置订单供应商方法
   *
   *  当CheckBox选择项发生变化时会触发该事件
   */
  function onbatchEdit(title) {
    console.log("触发按钮");
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    console.log(curSelected);
    openDialog(getKeyList(curSelected, "fgoodsid"), title);
  }

  /** 设置供应商信息 */
  function handlerSetSupplierInfo(row) {
    console.log(row);
    addDialog({
      title: "设置商品供货商信息",
      props: {
        formInline: {
          title: "设置商品供货商信息",
          fgoodsids: row.fgoodsid,
          orderno: orderId,
          paymethod: row.paymethod,
          price: row.purchaseprice,
          suppliername: row.suppliername,
          sendSideFreight: row.sendSideFreight,
          receiveSideFreight: row.receiveSideFreight
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(SupplierForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        FormRef.validate(async valid => {
          if (valid) {
            let { err } = await setGoodsSupplier(toRaw(curData));
            if (err.code == 0) {
              // 关闭弹窗表格
              done();
              message(`商品 ${curData.fgoodsids} 设置供应商信息成功`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              getOrderData(orderId);
            } else {
              done();
              message("设置失败", { type: "error" });
            }
          }
        });
      }
    });
  }

  /** 新增供货商信息弹出窗 */
  function openDialog(goodids, title) {
    if (title == "设置商品供货商信息") {
    } else {
      addDialog({
        title: "设置物流信息",
        props: {
          formInline: {
            title,
            fgoodsids: goodids,
            orderno: orderId,
            /**物流公司编号*/
            comcode: "shunfeng",
            /**物流单号 */
            trackingnum: ""
          }
        },
        width: "46%",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        contentRenderer: () => h(DeliverForm, { ref: formRef }),
        beforeSure: (done, { options }) => {
          const FormRef = formRef.value.getRef();
          const curData = options.props.formInline;
          FormRef.validate(async valid => {
            if (valid) {
              setOrderDeliver(toRaw(curData))
                .then(() => {
                  done();
                  message(`商品 ${curData.fgoodsids} 设置物流信息成功`, {
                    type: "success"
                  });
                  tableRef.value.getTableRef().clearSelection();
                  getOrderData(orderId);
                })
                .catch(error => {
                  console.error("设置物流信息失败:", error);
                  // 尝试从不同的错误结构中获取错误信息
                  // const errorMsg = error?.data?.msg ||
                  //                 error?.response?.data?.msg ||
                  //                 error?.msg ||
                  //                 `商品 ${curData.fgoodsids} 设置物流信息失败`;
                  message(error, {
                    type: "error"
                  });
                });
            }
          });
        }
      });
    }
  }

  /** 获取订单进度状态 */
  const getOrderStatus = (status: string) => {
    switch (status) {
      case "未发货":
        return 0;
      case "已发货":
        return 1;
      case "未开票":
        return 2;
      case "待回款":
        return 2;
      case "未回款":
        return 2;
      case "已回款":
        return 3;
    }
  };

  /**
   * @description: 单击设置供应商/快递信息
   * @param {*} id 订单号
   * @param {*} title 弹出窗口名称
   * @return {*}
   */
  const singleSelectionFun = (id, title = "") => {
    openDialog([id], title);
  };

  const copyOrderInfo = () => {
    // 构建要复制的文本
    const copyText = `
    订单编号：${orderDetail.value.orderno || orderDetail.value.id}
    单位名称：${orderDetail.value.purchasingunit}
    课题组名称：${orderDetail.value.departmentname}
    联系人姓名：${orderDetail.value.contactsname}
    联系人电话：${orderDetail.value.contactsphone}
    订单日期：${orderDetail.value.orderdate}
    收货人姓名：${receiptinfo.value.receivername}
    收货人电话：${receiptinfo.value.receiverphone}
    收货地址：${receiptinfo.value.address}`;
    // 复制到剪贴板
    const success = copyTextToClipboard(copyText);
    if (success) {
      message("复制成功", { type: "success" });
    } else {
      message("复制失败", { type: "error" });
    }
  };

  onMounted(() => {
    getOrderData(orderId);
  });

  return {
    formRef,
    loading,
    columns,
    selectedNum,
    orderDetail,
    receiptinfo,
    productinfo,
    orderStatus,
    totalprice,
    purchaseCosts,
    deliverCost,
    copyOrderInfo,
    getOrderData,
    openDialog,
    onbatchEdit,
    onSelectionCancel,
    handleSelectionChange
    // objectSpanMethod
  };
}

export function useDunningRecord(orderId) {
  // const formRef = ref();

  const dunningColumns: TableColumnList = [
    {
      prop: "id",
      label: "记录ID",
      width: "100px"
    },
    {
      prop: "orderNo",
      label: "订单编号",
      width: "180px"
    },
    {
      prop: "dunningMethod",
      label: "催款方式",
      width: "120px"
    },
    {
      prop: "dunningResult",
      label: "催款结果",
      width: "120px"
    },
    {
      prop: "communicationContent",
      label: "沟通内容",
      width: "200px"
    },
    {
      prop: "dunningTime",
      label: "催款时间",
      width: "180px",
      cellRenderer: ({ row }) => {
        // 使用 dayjs 格式化时间，将 ISO 格式转换为 YYYY-MM-DD HH:mm:ss 格式
        if (row.dunningTime) {
          return dayjs(row.dunningTime).format("YYYY-MM-DD HH:mm:ss");
        }
        return "";
      }
    },
    {
      prop: "dunningName",
      label: "催款人姓名",
      width: "120px"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const dunningDataList = ref();

  function openDialog(title: string = "新增", row: any) {
    let formRef = ref();
    let formInline = {};
    let submitFunc = (done, { options }) => {};
    if (title === "新增") {
      formInline = {
        orderNo: orderId,
        dunningMethod: "",
        dunningResult: "",
        communicationContent: "",
        dunningTime: "",
        dunningName: "",
        photoId: ""
      };

      submitFunc = (done, { options }) => {
        const currentData = options.props.formInline;
        console.log(currentData);
        const FormRef = formRef.value.getUploadRef();
        FormRef.submit();
        createDunningRecord(currentData).then(res => {
          if (res.status.code === 200) {
            message("新增成功", { type: "success" });
            done();
            getDunningRecord();
          } else {
            message(res.msg || "新增失败", { type: "error" });
          }
        });
      };
    }
    if (title === "编辑") {
      console.log(row);
      formInline = {
        id: row.id,
        orderNo: orderId,
        dunningMethod: row.dunningMethod,
        dunningResult: row.dunningResult,
        communicationContent: row.communicationContent,
        dunningTime: row.dunningTime,
        dunningName: row.dunningName
      };
      submitFunc = (done, { options }) => {
        const currentData = options.props.formInline;
        console.log(currentData);
        updateDunningRecord(currentData).then(res => {
          if (res.status.code === 200) {
            message("更新成功", { type: "success" });
            done();
            getDunningRecord();
          } else {
            message(res.msg || "更新失败", { type: "error" });
          }
        });
      };
    }

    addDialog({
      title: `${title}催款记录`,
      props: {
        // 表单初始化数据
        formInline
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(DunningForm, { ref: formRef }),
      beforeSure: submitFunc
    });
  }

  const getDunningRecord = async () => {
    const res = await queryDunningRecord({
      orderNo: orderId
    });
    if (res.status.code === 200) {
      dunningDataList.value = res.data || [];
    }
  };

  onMounted(() => {
    getDunningRecord();
  });

  return {
    dunningColumns,
    dunningDataList,
    openDialog
  };
}
